package com.ias.agdis_r.util;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.xmlpull.v1.XmlPullParser;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Environment;
import android.util.Log;
import android.util.Xml;

import com.ias.agdis_r.R;
import com.ias.agdis_r.bean.update.FTPServerInfoBean;
import com.ias.agdis_r.bean.update.UpadateApkBean;
import com.ias.agdis_r.bean.user.UserInfoBean;
import com.ias.agdis_r.manager.ActionManager;
import com.ias.agdis_r.manager.DataBaseManager;
import com.ias.agdis_r.manager.EffectManager;
import com.ias.agdis_r.manager.ServiceManage;
import com.ias.agdis_r.module.ParameterModel;
import com.ias.agdis_r.netservice.BaseService;
import com.ias.agdis_r.netservice.actions.PrivateNetService;
import com.ias.agdis_r.netservice.actions.PublicNetService;
import com.ias.agdis_r.netservice.actions.WifiNetService;
import com.ias.agdis_r.util.sdcard.SDcard;
import com.ias.agdis_r.util.sdcard.WriteLog;

public class UpdateUtil {

	public FTPClient ftpClient;
	private List<String> remotePathList = new ArrayList<String>();
	private List<String> localPathList = new ArrayList<String>();
	public static final String localFilePath = SDcard.getSDPATH()
			+ "/IASDownload/file/";// 本地存放临时配置文件路径
	public static final String localApkPath = SDcard.getSDPATH()
			+ "/IASDownload/apk/";// 本地存放临时APK路径
	private static UpdateUtil instance = null;
	private FTPServerInfoBean ftpServerInfo = null;
	private List<UpadateApkBean> updateApkList = null;
	private boolean isChecked = false; // 已经检测过
	private boolean needToUpdate = false; // 需要升级
	private int remoteFileVersion = 0; // 远程文件版本号
	private String remotePubUrl = "";
	private String remotePriUrl = "";
	private String updateurl =  "";   
	private BaseService usingService = null;
	private Context context = DataBaseManager.getInstance().getContext();

	public UpdateUtil() {
		// 创建FTP CLIENT
		ftpClient = new FTPClient();
	}

	public static UpdateUtil getInstance() {
		if (instance == null) {
			instance = new UpdateUtil();
		}

		return instance;
	}
	
	/**
	 * 升级版本
	 * 
	 * @param userInfo
	 */
	public void updateVersion(UserInfoBean userInfo) {
		//获取可用的网络服务
		BaseService usingService  = ServiceManage.getInstance().getUsingRestfulService();
		if(usingService==null)
		{
			return;
		}
		else
		{
			//保存使用的网络
			UpdateUtil.getInstance().setUsingService(usingService);
		}
		
		// 如果还未检测过&&检测到需要升级版本
		if (!UpdateUtil.getInstance().isChecked()) {
			
			String updateurl = "";
			String upr = "";  //后续，如果服务器可以返回，可以从服务器获取
			String upu = "";   //后续，如果服务器可以返回，可以从服务器获取
			if(S.isNotEmpty(upr))
			{
				//写入配置
				DataBaseManager.getInstance().insert(ParameterModel.UPDATE_CONFIG_PACKAGE,ParameterModel.T_UPDATE_CONFIG,ParameterModel.AGDIS_PRI_UP_URL,upr); 
			}
			else
			{
				upr = DataBaseManager.getInstance().getString(ParameterModel.UPDATE_CONFIG_PACKAGE,ParameterModel.T_UPDATE_CONFIG,
						ParameterModel.AGDIS_PRI_UP_URL);
			}
			if(S.isNotEmpty(upu))
			{
				//写入配置
				DataBaseManager.getInstance().insert(ParameterModel.UPDATE_CONFIG_PACKAGE,ParameterModel.T_UPDATE_CONFIG,ParameterModel.AGDIS_PUB_UP_URL,upu); 
			}
			else
			{
				upu = DataBaseManager.getInstance().getString(ParameterModel.UPDATE_CONFIG_PACKAGE,ParameterModel.T_UPDATE_CONFIG,
						ParameterModel.AGDIS_PUB_UP_URL);
			}
			
			//如果选择了专网
			if(usingService.getClass().equals(PrivateNetService.class))
			{
				updateurl = upr;
			}
			else if(usingService.getClass().equals(PublicNetService.class)||
					usingService.getClass().equals(WifiNetService.class))
			{
				updateurl = upu;
			}
			
			if (S.isNotEmpty(updateurl))
			{
				int addPoint = updateurl.lastIndexOf("/");
				if (addPoint >= 10)// 至少在http://xx.xx.xx.xx后
				{
					String mfg = S.valueOf(userInfo.getMfg());
					String sb = updateurl.substring(0, addPoint+1);	// 含最后一个/
					String se = updateurl.substring(addPoint);	// 含最后一个/
					updateurl = sb + mfg + se;
					WriteLog.getInstance().writeLog("检测版本升级URL:"+updateurl);
					UpdateUtil.getInstance().setUpdateURL(updateurl);
					//检测升级版本
					UpdateUtil.getInstance().checkUpdateVersion();
				}
			}
		}

	}
	/**
	 * 获取升级的APK信息列表
	 * 
	 * @return
	 */
	public List<UpadateApkBean> getUpdateAPKList() {
		return this.updateApkList;
	}

	public int getRemoteFileCount() {
		return remotePathList.size();
	}

	public void setUpdateURL(String updateurl) {
		// 如果升级文件路径不为空，保存
		if (S.isNotEmpty(updateurl)) {
			this.updateurl = updateurl;
		}
	}

	public String getUpdateURL() {
		return this.updateurl;
	}

	public int getLocalFileCount() {
		return localPathList.size();
	}

	/**
	 * 设置FTP配置
	 * 
	 * @param ftpServerInfo
	 */
	public void setFTPServerInfo(FTPServerInfoBean ftpServerInfo) {
		this.ftpServerInfo = ftpServerInfo;
	}

	/**
	 * 已经检测过
	 */
	public boolean isChecked() {
		return this.isChecked;
	}

	/**
	 * 是否需要升级
	 */
	public boolean isNeedToUpdate() {
		return this.needToUpdate;
	}

	/**
	 * 连接到FTP服务器
	 * 
	 * @param hostname
	 *            主机名
	 * @param port
	 *            端口
	 * @param username
	 *            用户名
	 * @param password
	 *            密码
	 * @return 是否连接成功
	 * @throws IOException
	 */
	public boolean ftpConnect() throws IOException {
		// 如果没有FTP配置信息
		if (ftpServerInfo == null) {
			return false;
		}

		ftpClient.connect(getFtpIp(ftpServerInfo), ftpServerInfo.getPort());
		if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
			if (ftpClient
					.login(ftpServerInfo.getUser(), ftpServerInfo.getPwd())) {

				// 下面三行代码必须要，而且不能改变编码格式，否则不能正确下载中文文件
				ftpClient.setControlEncoding("GBK");
				FTPClientConfig conf = new FTPClientConfig(
						FTPClientConfig.SYST_UNIX);
				conf.setServerLanguageCode("zh");
				// 设置被动模式
				ftpClient.enterLocalPassiveMode();
				// 设置以二进制方式传输
				ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

				return true;
			}
		}
		ftpDisconnect();
		return false;
	}

	/** */
	/**
	 * 断开与远程服务器的连接
	 * 
	 * @throws IOException
	 */
	public void ftpDisconnect() {
		if (ftpClient.isConnected()) {
			try {
				ftpClient.disconnect();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public void getFilePathList(String remoteFolder) {
		// 检查远程文件是否存在
		try {
			Log.i("AGDIS", "遍历FTP路径：" + remoteFolder);
			FTPFile[] files = ftpClient.listFiles(remoteFolder);
			if (files.length == 0) {
				Log.i("AGDIS", "该目录下没有文件");
				return;
			}
			for (FTPFile file : files) {
				if (file.isFile()) {
					String remotePath = remoteFolder + file.getName();
					Log.i("AGDIS", "远程文件：" + remotePath);
					remotePathList.add(remotePath);
				} else {
					String subRemoteFolder = remoteFolder + file.getName()
							+ File.separator;
					Log.i("AGDIS", "远程文件夹：" + subRemoteFolder);
					getFilePathList(subRemoteFolder);
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void downLoadFtpFile(ProgressDialog pd) {
		InputStream in = null;
		ByteArrayOutputStream byteOutStream = new ByteArrayOutputStream();
		FileOutputStream fileOutStream = null;
		try {
			if (!ftpClient.isConnected()) {
				boolean isCon = this.ftpConnect();
				if (!isCon) {
					return;
				}
			}
			pd.setMax(this.getRemoteFileCount());
			pd.setProgress(0);
			for (String remotePath : remotePathList) {
				// 获取到文件的大小
				in = ftpClient.retrieveFileStream(remotePath);
				String savePath = localFilePath + remotePath.replace("\\", "/");

				WriteLog.getInstance().writeLog(
						context.getString(R.string.UU_1) + remotePath + context.getString(R.string.UU_2) + context.getString(R.string.UU_3) + savePath);
				if (in == null) {
					continue;
				}
				// 检测文件路径下的文件夹，如果没有文件夹，创建文件夹
				checkForder(savePath);
				File f = new File(savePath);
				if (f.exists()) {
					f.delete();
				}
				f.createNewFile();

				// 重置byteOutStream
				byteOutStream.reset();
				// 创建一个Buffer字符串
				byte[] buffer = new byte[1024];
				// 每次读取的字符串长度，如果为-1，代表全部读取完毕
				int len = 0;
				// 使用一个输入流从buffer里把数据读取出来
				while ((len = in.read(buffer)) != -1) {
					// 用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
					byteOutStream.write(buffer, 0, len);
				}

				byte[] data = byteOutStream.toByteArray();
				// 创建输出流
				fileOutStream = new FileOutputStream(f);
				// 写入数据
				fileOutStream.write(data);
				// 关闭输出流
				fileOutStream.close();

				// 调用完之后必须调用completePendingCommand释放,否则FTP会断开连接
				ftpClient.completePendingCommand();
				localPathList.add(savePath);
				pd.setProgress(localPathList.size());
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (in != null) {
					in.close();
					in = null;
				}
				if (byteOutStream != null) {
					byteOutStream.close();
					byteOutStream = null;
				}
				if (fileOutStream != null) {
					fileOutStream.close();
					fileOutStream = null;
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			// 关闭FTP连接
			ftpDisconnect();
		}

	}

	/**
	 * 为指定路径创建文件夹
	 * 
	 * @param path
	 */
	public void checkForder(String filePath) {
		if (S.isEmpty(filePath)) {
			return;
		}
		String[] forderNames = filePath.split(File.separator);
		String foderPath = "";
		if (forderNames.length == 1) {
			return;
		}
		for (int i = 0; i < forderNames.length - 1; i++) {
			if (S.isEmpty(forderNames[i])) {
				continue;
			}
			foderPath = foderPath + File.separator + forderNames[i];
		}
		File file = new File(foderPath);
		if (!file.exists()) {
			file.mkdirs();
		}
	}

	/**
	 * 用pull解析器解析服务器返回的xml文件 (xml封装了版本号)
	 */
	public void loadUpdateXml(InputStream is) throws Exception{  
	    XmlPullParser  parser = Xml.newPullParser();
	    parser.setInput(is, "utf-8");//设置解析的数据源     
	    int type = parser.getEventType(); 
	    UpadateApkBean info = null;
	    FTPServerInfoBean ftpServerInfo = null;
	    while(type != XmlPullParser.END_DOCUMENT ){   
	        switch (type) {   
	        case XmlPullParser.START_DOCUMENT://判断当前事件是否是文档开始事件   
	        	 updateApkList=new ArrayList<UpadateApkBean>(); 
	        	 break;
	        case XmlPullParser.START_TAG:   
	        	if("app".equals(parser.getName()))
	        	{
	        		info = new UpadateApkBean();//实体 
	        		//包名应用包名
	        		info.setPack(parser.getAttributeValue(0));
	        	}else if ("ftp".equals(parser.getName())){ 
	        		ftpServerInfo = new FTPServerInfoBean();
	            } else if("version".equals(parser.getName())){   
	                info.setVersion(parser.nextText()); //获取版本号    
	            }else if ("puburl".equals(parser.getName())){   
	                info.setPuburl(parser.nextText()); //获取要升级的公网URL
	            }else if ("priurl".equals(parser.getName())){   
	                info.setPriurl(parser.nextText()); //获取要升级的专网URL  
	            }else if ("desc".equals(parser.getName())){    
	                info.setDescription(parser.nextText()); //获取该文件的信息    
	            }else if("user".equals(parser.getName())){
	            	ftpServerInfo.setUser(parser.nextText());
	            }else if("pwd".equals(parser.getName())){
	            	ftpServerInfo.setPwd(parser.nextText());
	            }else if("pubip".equals(parser.getName())){
	            	ftpServerInfo.setPubip(parser.nextText());
	            }else if("priip".equals(parser.getName())){
	            	ftpServerInfo.setPriip(parser.nextText());
	            }else if("port".equals(parser.getName())){            	
	            	int port = 0;
					try {
						port = Integer.parseInt(parser.nextText().toString());
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					ftpServerInfo.setPort(port);
	            }
	            break;    
	        case XmlPullParser.END_TAG:
                if("app".equals(parser.getName())){
                	updateApkList.add(info);
                	WriteLog.getInstance().writeLog(context.getString(R.string.UU_4)+info.getVersion()+"|puburl:"+info.getPuburl()+"|priurl:"+info.getPriurl()+"|description:"+info.getDescription()+"|pack:"+info.getPack());
                    info=null;
                }
                else if("ftp".equals(parser.getName())){	
                	UpdateUtil.getInstance().setFTPServerInfo(ftpServerInfo);
                	WriteLog.getInstance().writeLog(context.getString(R.string.UU_5)+ftpServerInfo.getUser()+"|url:"+ftpServerInfo.getPwd()+"|pubIp:"+ftpServerInfo.getPubip()+"|priIp:"+ftpServerInfo.getPriip()+"|port:"+ftpServerInfo.getPort());
                }
	        }
	        type = parser.next();   
	    }     
	}  
	
	public void setUsingService(BaseService usingService)
	{
		this.usingService = usingService;
	}
	
	public String getApkUrl(UpadateApkBean info)
	{
		String url = "";
		if(usingService == null)
		{

		}
		else if(usingService.getClass().equals(PrivateNetService.class))
		{
			url = info.getPriurl();
		}
		else if(usingService.getClass().equals(PublicNetService.class)||
				usingService.getClass().equals(WifiNetService.class))
		{
			url = info.getPuburl();
		}
		
		return url;
	}
	
	public String getFtpIp(FTPServerInfoBean info)
	{
		String url = "";
		if(usingService == null)
		{

		}
		else if(usingService.getClass().equals(PrivateNetService.class))
		{
			url = info.getPriip();
		}
		else if(usingService.getClass().equals(PublicNetService.class)||
				usingService.getClass().equals(WifiNetService.class))
		{
			url = info.getPubip();
		}
		
		return url;
	}
	public void checkUpdateVersion() {
		if (!isChecked()) {
			this.isChecked = true;
			new Thread() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					super.run();
					UpdateUtil.getInstance().checkUpdate();
				}
			}.start();
		}
	}

	/**
	 * 检测是否需要升级版本
	 */
	private boolean checkUpdate() {
		this.isChecked = true;
		if(checkAppVersion()|checkFileVersion())
		{
			   //显示升级版本的提示框
			   ActionManager.getInstance().showDialogDownLoad();
			   this.needToUpdate = true;
			   return true;
		}
		return needToUpdate;
	}

	/**
	 * 检测应用版本
	 */
	public boolean checkAppVersion() {
		try {
			WriteLog.getInstance().writeLog(context.getString(R.string.UU_6) + updateurl);
			System.out.println(context.getString(R.string.UU_6) + updateurl);
			// 包装成url的对象
			URL url = new URL(updateurl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(3000);
			InputStream is = conn.getInputStream();
			String result = inputStream2String(is);
			WriteLog.getInstance().writeLog(context.getString(R.string.UU_7) + result);
			System.out.println(context.getString(R.string.UU_7) + result);
			loadUpdateXml(new ByteArrayInputStream(result.getBytes("UTF-8")));

			if (updateApkList == null || updateApkList.size() == 0) {
				return false;
			}

			List<UpadateApkBean> updateList2 = new ArrayList<UpadateApkBean>();
			for (UpadateApkBean updateInfo : updateApkList) {
				int remoteVersion = Integer.parseInt(updateInfo.getVersion());
				int localVersion = getSoftWareVersion(updateInfo.getPack());
				WriteLog.getInstance().writeLog("检测版本："+updateInfo.getPack()+"服务器端版本："+remoteVersion+"|本地版本："+localVersion);
				//如果本地未安装的APP，不进行更新
				if (localVersion!=0&&remoteVersion > localVersion) {
					updateList2.add(updateInfo);
				}
			}
			updateApkList = updateList2;
			if (updateApkList != null && updateApkList.size() > 0) {
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
			WriteLog.getInstance().writeLog(context.getString(R.string.UU_8)+",Exception:"+ e.getMessage());
		}

		return false;
	}

	/**
	 * 读取远程文件版本
	 * 
	 * @return
	 */
	public int readRemoteFileVersion(String remotePath)
	{
		InputStream in = null;
		OutputStream out = null;
		try 
		{
			if(!ftpClient.isConnected())
			{
				boolean isCon = this.ftpConnect();
				if (!isCon) {
					return 0;
				}
			}
			//获取到文件的大小     
			in = ftpClient.retrieveFileStream(remotePath);	
			if(in!=null)
			{
				 XmlPullParser  parser = Xml.newPullParser();
				 parser.setInput(in, "utf-8");//设置解析的数据源     
				 int type = parser.getEventType(); 
				 while(type != XmlPullParser.END_DOCUMENT )
				 {   
				     switch (type) {   
				     	case XmlPullParser.START_DOCUMENT://判断当前事件是否是文档开始事件    
				        	 	break;
				     	case XmlPullParser.START_TAG:  
				     		if("map".equals(parser.getName()))
				        	{
				        		
				        	}else if(ParameterModel.CONFIG_VERSION.equals(parser.getAttributeValue(0))){			     			
				     			String sversion = parser.nextText();
				     			remoteFileVersion = Integer.parseInt(sversion);
				     		}
				     		else if(ParameterModel.AGDIS_PUB_UP_URL.equals(parser.getAttributeValue(0))){ 		
				     			remotePubUrl = parser.nextText();
				     		}
				     		else if(ParameterModel.AGDIS_PRI_UP_URL.equals(parser.getAttributeValue(0))){ 		
				     			remotePriUrl = parser.nextText();
				     		}
				     		break;    
				     	case XmlPullParser.END_TAG:{
				     		break;
				     	} 
				     }
				     type = parser.next();  
				 }
			}
			//调用完之后必须调用completePendingCommand释放,否则FTP会断开连接
			ftpClient.completePendingCommand();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		finally{
			try {
				if(in!=null)
				{
					in.close();
					in = null;
				}
				if(out!=null)
				{
					out.close();
					in = null;
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		return remoteFileVersion;
	}

	/**
	 * 检测配置文件版本
	 */
	public boolean checkFileVersion() {
		try {
			int localVersion = DataBaseManager.getInstance().getInt(
					ParameterModel.UPDATE_CONFIG_PACKAGE,
					ParameterModel.T_UPDATE_CONFIG,
					ParameterModel.CONFIG_VERSION);
			WriteLog.getInstance().writeLog(context.getString(R.string.localVersion) + localVersion);
			System.out.println(context.getString(R.string.localVersion) + localVersion);
			boolean isCon = this.ftpConnect();
			if (!isCon) {
				return false;
			}
			this.getFilePathList("");
			if (getRemoteFileCount() == 0) {
				return false;
			}

			for (String remotePath : remotePathList) {
				if (S.isNotEmpty(remotePath)
						&& remotePath.indexOf(ParameterModel.T_UPDATE_CONFIG) > -1) {
					// 读取远程配置文件版本号
					readRemoteFileVersion(remotePath);
					if (remoteFileVersion > localVersion) {
						WriteLog.getInstance().writeLog(
								context.getString(R.string.UU_9) + remoteFileVersion
										+ context.getString(R.string.UU_10) + localVersion
										+ context.getString(R.string.UU_11));
						System.out.println(context.getString(R.string.UU_9) + remoteFileVersion
								+ context.getString(R.string.UU_10) + localVersion
								+ context.getString(R.string.UU_11));
						return true;
					} else {
						// 如果不需要升级版本，删除远程文件路径列表
						remotePathList.clear();
						WriteLog.getInstance().writeLog(
								context.getString(R.string.UU_9) + remoteFileVersion + context.getString(R.string.UU_12)
										+ localVersion + context.getString(R.string.UU_13));
						System.out.println(
								context.getString(R.string.UU_9) + remoteFileVersion + context.getString(R.string.UU_12)
										+ localVersion + context.getString(R.string.UU_13));
						return false;
					}
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// 如果不需要升级版本，删除远程文件路径列表
		remotePathList.clear();
		return false;
	}

	/**
	 * @author huzedong 上传文件接口
	 * @param url
	 *            ftp服务器的地址
	 * @param port
	 *            ftp服务器的端口
	 * @param username
	 *            ftp用户名
	 * @param password
	 *            ftp密码
	 * @param remotePath
	 *            远程路径
	 * @param fileNamePath
	 *            要上传的文件路径
	 * @param fileName
	 *            要上传的文件名
	 * @return
	 */
	public String ftpUpload(String url, String port, String username,
			String password, String remotePath, String fileNamePath,
			String fileName) {
		FileInputStream fis = null;
		String returnMessage = "0";
		try {
			ftpClient.connect(url, Integer.parseInt(port));
			boolean loginResult = ftpClient.login(username, password);
			int returnCode = ftpClient.getReplyCode();
			if (loginResult && FTPReply.isPositiveCompletion(returnCode)) {// 如果登录成功
				ftpClient.makeDirectory(remotePath);
				// 设置上传目录
				ftpClient.changeWorkingDirectory(remotePath);
				ftpClient.setBufferSize(1024);
				ftpClient.setControlEncoding("UTF-8");
				ftpClient.enterLocalPassiveMode();
				fis = new FileInputStream(fileNamePath + fileName);
				ftpClient.storeFile(fileName, fis);
				returnMessage = "1"; // 上传成功
			} else {// 如果登录失败
				returnMessage = "0";
			}
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException(context.getString(R.string.UU_14), e);
		} finally {
			// IOUtils.closeQuietly(fis);
			try {
				ftpClient.disconnect();
			} catch (IOException e) {
				e.printStackTrace();
				throw new RuntimeException(context.getString(R.string.UU_15), e);
			}
		}
		return returnMessage;
	}

	/**
	 * @author huzedong 上传文件接口
	 * @param FTPServerInfoBean
	 *            ftp服务器信息
	 * @param remotePath
	 *            远程路径
	 * @param fileNamePath
	 *            要上传的文件路径
	 * @param fileName
	 *            要上传的文件名
	 * @return
	 */
	public String ftpUpload(FTPServerInfoBean ftpserverinfobean,
			String remotePath, String fileNamePath, String fileName) {
		FileInputStream fis = null;
		String returnMessage = "0";
		try {
		     ftpClient.connect(getFtpIp(ftpserverinfobean), ftpserverinfobean.getPort());  
		     boolean loginResult = ftpClient.login(ftpserverinfobean.getUser(), ftpserverinfobean.getPwd());  
			int returnCode = ftpClient.getReplyCode();
			if (loginResult && FTPReply.isPositiveCompletion(returnCode)) {// 如果登录成功
				ftpClient.makeDirectory(remotePath);
				// 设置上传目录
				ftpClient.changeWorkingDirectory(remotePath);
				ftpClient.setBufferSize(1024);
				ftpClient.setControlEncoding("UTF-8");
				ftpClient.enterLocalPassiveMode();
				fis = new FileInputStream(fileNamePath + fileName);
				ftpClient.storeFile(fileName, fis);
				returnMessage = "1"; // 上传成功
			} else {// 如果登录失败
				returnMessage = "0";
			}
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException(context.getString(R.string.UU_14), e);
		} finally {
			// IOUtils.closeQuietly(fis);
			try {
				ftpClient.disconnect();
			} catch (IOException e) {
				e.printStackTrace();
				throw new RuntimeException(context.getString(R.string.UU_15), e);
			}
		}
		return returnMessage;
	}

	/**
	 * 从服务器下载apk
	 * 
	 * @param path
	 * @param pd
	 * @return
	 * @throws Exception
	 */
	public  File downloadAPK(UpadateApkBean updateInfo, ProgressDialog pd) throws Exception{  
		 //如果相等的话表示当前的sdcard挂载在手机上并且是可用的    
		 if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
			 String apkurl = getApkUrl(updateInfo);
			 WriteLog.getInstance().writeLog(context.getString(R.string.UU_16)+apkurl);
		     URL url = new URL(apkurl);   
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(5000);
			pd.setProgress(0);
			// 获取到文件的大小
			pd.setMax(conn.getContentLength());
			InputStream is = conn.getInputStream();
			String apkPath = UpdateUtil.localApkPath + updateInfo.getPack()
					+ ".apk";
			UpdateUtil.getInstance().checkForder(apkPath);
			updateInfo.setSavePath(apkPath);
			WriteLog.getInstance().writeLog(context.getString(R.string.UU_17) + apkPath);
			File file = new File(apkPath);
			FileOutputStream fos = new FileOutputStream(file);
			BufferedInputStream bis = new BufferedInputStream(is);
			byte[] buffer = new byte[1024];
			int len;
			int total = 0;
			while ((len = bis.read(buffer)) != -1) {
				fos.write(buffer, 0, len);
				total += len;
				// 获取当前下载量
				pd.setProgress(total);
			}
			fos.close();
			bis.close();
			is.close();
			return file;
		} else {
			return null;
		}
	}

	/**
	 * 获取当前程序的版本号
	 */
	private int getSoftWareVersion(String packName) {
		int curVersion = 0;
		try {
			curVersion = DataBaseManager.getInstance().getContext()
					.getPackageManager().getPackageInfo(packName, 0).versionCode; // package.name根据实际名字定义，内容在androidMainfest.xml文件中
		} catch (NameNotFoundException e) {

			e.printStackTrace();
		}
		return curVersion;
	}
	
	public String inputStream2String(InputStream is) {
		String result = "";
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();
		String line = null;
		try {
			while ((line = reader.readLine()) != null) {

				sb.append(line);
			}
			result = sb.toString();

		} catch (IOException e) {

			e.printStackTrace();

		} finally {

			try {

				is.close();

			} catch (IOException e) {

				e.printStackTrace();

			}

		}
		return result;
	}

	/**
	 * 初始化配置文件
	 */
	public void initConfigFile() {
		try {
			for (String localPath : localPathList) {
				// 将保存下载文件的路径改为SD卡根目录
				String copyPath = localPath.replace(localFilePath,
						SDcard.getSDPATH() + File.separator);
				checkForder(copyPath);
				copyFile(localPath, copyPath);
				delDownloadFile(localPath);
			}
			if(S.isNotEmpty(remotePubUrl))
			{
				//写入升级后的公网URL
				DataBaseManager.getInstance().insert(ParameterModel.UPDATE_CONFIG_PACKAGE,ParameterModel.T_UPDATE_CONFIG,ParameterModel.AGDIS_PUB_UP_URL,remotePubUrl); //写入升级的URL
			}
			
			if(S.isNotEmpty(remotePriUrl))
			{
				//写入升级后的专网URL
				DataBaseManager.getInstance().insert(ParameterModel.UPDATE_CONFIG_PACKAGE,ParameterModel.T_UPDATE_CONFIG,ParameterModel.AGDIS_PRI_UP_URL,remotePriUrl); //写入升级的URL
			}
			
			//写入升级后的版本号
			DataBaseManager.getInstance().insert(ParameterModel.UPDATE_CONFIG_PACKAGE,ParameterModel.T_UPDATE_CONFIG,ParameterModel.CONFIG_VERSION,remoteFileVersion); //写入版本号
		
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_UPTO,
					context.getString(R.string.UU_18), false);
		}
	}

	/**
	 * 删除下载储存的配置文件
	 * 
	 * @param localPath
	 */
	public void delDownloadFile(String localPath) {
		File file = new File(localPath);
		if (file.exists()) {
			file.delete();
		}
	}

	/**
	 * 复制单个文件
	 * 
	 * @param oldPath
	 *            String
	 * @param newPath
	 *            String
	 * @return boolean
	 */
	public void copyFile(String oldPath, String newPath) {
		try {
			int bytesum = 0;
			int byteread = 0;
			File oldfile = new File(oldPath);
			// 如果
			if (oldfile.exists()) { // 文件存在时
				if (oldPath.indexOf(ParameterModel.T_UPDATE_CONFIG) > -1) {
					Log.i("AGDIS", oldPath + "为记录版本号文件不进行同步");
					return;
				}
				WriteLog.getInstance().writeLog(
						context.getString(R.string.UU_19) + oldfile + context.getString(R.string.UU_20) + newPath);
				System.out.println(
						context.getString(R.string.UU_19) + oldfile + context.getString(R.string.UU_20) + newPath);
				InputStream inStream = new FileInputStream(oldPath); // 读入原文件
				FileOutputStream fs = new FileOutputStream(newPath);
				byte[] buffer = new byte[1024];
				while ((byteread = inStream.read(buffer)) != -1) {
					bytesum += byteread; // 字节数 文件大小
					System.out.println(bytesum);
					fs.write(buffer, 0, byteread);
				}
				inStream.close();
			}
		} catch (Exception e) {
			System.out.println("复制单个文件操作出错");
			e.printStackTrace();

		}

	}
}
